package net.pingfang.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: CM
 * @Date: 2022/3/21 18:54
 * @Description:
 */
@Configuration
@Component
@Slf4j
public class RestTemplateConfig {
    public static RestTemplate restTemplate;
    @Bean
    public static RestTemplate getInstance() {
        if (restTemplate==null) {
            log.info("实例化restTemplate");
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // 设置连接超时时间
            requestFactory.setConnectTimeout(1000);
            // 设置读取超时时间
            requestFactory.setReadTimeout(2000);
            restTemplate = new RestTemplate();
            List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
            for (HttpMessageConverter<?> httpMessageConverter : list) {
                if (httpMessageConverter instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
                    break;
                }
            }
        }
        return restTemplate;
    }
}
